package it.polimi.traveldream.ejb;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import it.polimi.traveldream.ejb.management.HotelDTO;
import it.polimi.traveldream.ejb.management.HotelMgr;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class BeanHotel implements HotelMgr {
	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;

	private boolean add;
	

	@Override
	public void save(HotelDTO hotel) {
		Hotel hotelNew = new Hotel(hotel);
		em.persist(hotelNew);
		
	}

	@Override
	public void update(HotelDTO hotel) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public List<HotelDTO> getHotels() {
		List<Hotel> lHotel = em.createNamedQuery(Hotel.FIND_ALL,Hotel.class).getResultList();
		List<HotelDTO> list = new ArrayList<HotelDTO>();
		HotelDTO temp;
		for (Hotel hotel : lHotel) {
			temp = convertToDTO(hotel);
			list.add(temp);
		}
		return list;
	}
	
	
	public HotelDTO convertToDTO(Hotel hotel){
		HotelDTO hotelDTO = new HotelDTO();
		hotelDTO.setNome(hotel.getNome());
		hotelDTO.setCitta(hotel.getCitta());
		hotelDTO.setPostiRimanenti(hotel.getPostiRimanenti());
		hotelDTO.setPrezzoSingolo(hotel.getPrezzoSingolo());
		hotelDTO.setIdHotel(hotel.getIdHotel());
		return hotelDTO;
		
	}
	
	@Override
	public void elimina(HotelDTO hot){
		Query query=em.createNamedQuery(Hotel.DELETE,Hotel.class);
		System.out.println("ID HOTEL" + hot.getIdHotel());
		
		query.setParameter(1, hot.getIdHotel());
		query.executeUpdate();
		
	}

	@Override
	public List<HotelDTO> listaHotel(){
		Query query=em.createNamedQuery(Hotel.FIND_ALL,Hotel.class);
		query.executeUpdate();
		List<Hotel> lists=castList(Hotel.class,query.getResultList());
        List<HotelDTO> list=convertToHotelDTO(lists);
		return list;	}
	
	private List<HotelDTO> convertToHotelDTO (List<Hotel> hotelDaConv) {
		List<HotelDTO> returnedItems=new ArrayList<HotelDTO>();
		Iterator<Hotel> iter=hotelDaConv.iterator();
		while(iter.hasNext()){
			returnedItems.add(convertToDTO(iter.next()));
		}
		return returnedItems;
	}
	
	private static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
	    List<T> r = new ArrayList<T>(c.size());
	    for(Object o: c)
	      r.add(clazz.cast(o));
	    return r;
	}

	@Override
	public HotelDTO cercaById(int id) {
		Query query = em.createNamedQuery(Hotel.FINDID,Hotel.class);
		System.out.println("HERE " + id);
		query.setParameter(1, id);
		Hotel hotel = (Hotel) query.getResultList().get(0);
		HotelDTO ret = convertToDTO(hotel);
		return ret;
	}
}
